<?php

namespace app\api\model;

use think\Model;
use think\Db;

class SystemRole extends Model
{
    // 表名
    protected $name = 'system_role';

    // 自动时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    // 类型转换
    protected $type = [
        'role_sort' => 'integer',
        'status' => 'integer'
    ];

    /**
     * 关联菜单
     */
    public function menus()
    {
        return $this->belongsToMany('SystemMenus', 'system_role_menus', 'menu_id', 'role_id');
    }

    /**
     * 获取角色列表
     */
    public function getRoleList($params, $page, $size, $system_user_id = 0)
    {
        $where = [];

        if (!empty($params['roleName'])) {
            $where[] = ['role_name', 'like', '%' . $params['roleName'] . '%'];
        }

        if (!empty($params['roleKey'])) {
            $where[] = ['role_key', 'like', '%' . $params['roleKey'] . '%'];
        }

        if (isset($params['status']) && $params['status'] !== '') {
            $where[] = ['status', '=', $params['status']];
        }

        if ($system_user_id) {
            $where['system_user_id'] = $system_user_id;
        }

        $count = $this->where($where)->count();
        $list = $this->where($where)->where("id", ">", 2)
            ->order('role_sort asc, create_time desc')
            ->page($page, $size)
            ->select();

        return [
            'list' => $list,
            'total' => $count
        ];
    }

    /**
     * 添加角色
     */
    public function addRole($data)
    {
        Db::startTrans();
        try {
            // 添加角色
            $role = $this->create([
                'role_name' => $data['role_name'],
                'role_key' => $data['role_key'],
                'role_sort' => $data['role_sort'] ?? 0,
                'status' => $data['status'] ?? 1,
                'remark' => $data['remark'] ?? '',
                'custom_org_ids'=>implode($data['custom_org_ids'])?? '',
                'select_data_permission'=>$data['select_data_permission'] ?? '',
                'system_user_id' => $data['system_user_id'] ?? '',
            ]);

            // 添加角色菜单关联
            if (!empty($data['menu_ids'])) {
                $menuData = [];
                foreach ($data['menu_ids'] as $menuId) {
                    $menuData[] = [
                        'role_id' => $role->id,
                        'menu_id' => $menuId
                    ];
                }
                Db::name('system_role_menus')->insertAll($menuData);
            }

            Db::commit();
            return $role->id;
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
    }

    /**
     * 更新角色
     */
    public function updateRole($id, $data)
    {
        Db::startTrans();
        try {
            // 更新角色
            $this->where('id', $id)->update([
                'role_name' => $data['role_name'],
                'role_key' => $data['role_key'],
                'role_sort' => $data['role_sort'] ?? 0,
                'status' => $data['status'] ?? 1,
                'remark' => $data['remark'] ?? '',
                'custom_org_ids'=> implode(',',$data['custom_org_ids']) ?? '',
                'select_data_permission'=>$data['select_data_permission'] ?? '',
            ]);

            // 删除原有菜单关联
            Db::table('system_role_menus')->where('role_id', $id)->delete();

            // 添加新的菜单关联
            if (!empty($data['menuIds'])) {
                $menuData = [];
                foreach ($data['menuIds'] as $menuId) {
                    $menuData[] = [
                        'role_id' => $id,
                        'menu_id' => $menuId
                    ];
                }
                Db::table('system_role_menus')->insertAll($menuData);
            }

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
    }

    /**
     * 更新角色
     */
    public function updateRole2($id, $data)
    {
        Db::startTrans();
        try {

            // 删除原有菜单关联
            Db::table('system_role_menus')->where('role_id', $id)->delete();

            // 添加新的菜单关联
            if (!empty($data['menuIds'])) {
                $menuData = [];
                foreach ($data['menuIds'] as $menuId) {
                    $menuData[] = [
                        'role_id' => $id,
                        'menu_id' => $menuId
                    ];
                }
                Db::table('system_role_menus')->insertAll($menuData);
            }

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
    }

    /**
     * 更新角色
     */
    public function updateRole3($id, $system_user_id, $data)
    {
        Db::startTrans();
        try {

            // 删除原有菜单关联
            Db::table('system_role_menus')->where(['role_id' => $id, 'system_user_id' => $system_user_id])->delete();

            // 添加新的菜单关联
            if (!empty($data['menuIds'])) {
                $menuData = [];
                foreach ($data['menuIds'] as $menuId) {
                    $menuData[] = [
                        'role_id' => $id,
                        'system_user_id'=>$system_user_id,
                        'menu_id' => $menuId
                    ];
                }
                Db::table('system_role_menus')->insertAll($menuData);
            }

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
    }


    /**
     * 获取角色详情（包含菜单ID）
     */
    public function getRoleWithMenus($id,$system_user_id=0)
    {
        $role = $this->find($id);
        if (!$role) {
            return null;
        }

        if($system_user_id){
            $menuIds = Db::name('system_role_menus')
                ->where('role_id', $id)->where('system_user_id', $system_user_id)
                ->column('menu_id');
        }else{
            $menuIds = Db::name('system_role_menus')
                ->where('role_id', $id)
                ->column('menu_id');
        }


        $role = $role->toArray();
        $role['menu_ids'] = $menuIds;

        return $role;
    }
}